<template>
  <!-- 已发布新闻列表 -->
  <base-breadcrumb class="releasedNews-container">
    <searchData :search-data="searchArr" :need-filter-empty-val="false" @search="handleSearch" />
    <a-card :bordered="false">
      <!-- <title-name title="新闻列表" /> -->
      <div class="pub-table-select-count mb10">
        <a-icon type="info-circle" theme="twoTone" />
        <span>
          共计：
          <a>{{ totalInfo.totalNum || 0 }} 个</a>
        </span>
      </div>
      <list-table
        ref="table"
        row-key="id"
        :columns="columns"
        :request="loadData"
        show-size-changer
        :isScrollX="false"
        show-quick-jumper
        show-pagination="auto"
      >
        <!-- 序号 -->
        <div slot="index" slot-scope="text, record, index" style="position: relative">
          <a-icon
            v-if="record.topStatus == 1"
            type="like"
            theme="filled"
            style="color: #f19149; font-size: 18px; position: absolute; left: 10px; top: 1px"
          />{{ index + 1 }}
        </div>
        <!-- 新闻类别 -->
        <a slot="type" slot-scope="text" style="cursor: auto">【{{ filterLabel(text, 'type') }}】</a>
        <!-- 新闻标题 -->
        <div slot="name" slot-scope="text, record" @click="handleUpdate(record, 'look')">
          <a-row
            type="flex"
            justify="space-between"
            align="middle"
            :style="{ color: isViewed(record.id) ? '#999' : 'inherit' }"
          >
            <div style="text-decoration: underline; white-space: break-spaces; cursor: pointer; width: 90%">{{ text }}</div>
            <a-row type="flex" align="middle">
              <a-icon type="eye" style="font-size: 18px; padding-right: 3px" />
              {{ record.readingQuantity || 0 }}
            </a-row>
          </a-row>
        </div>
      </list-table>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import { getList2, increaseReadingQuantity, getContentById } from '@/api/partyMasses/partyManage/newsManage.js'
import { NEWS_TYPE } from './model'
import { Ellipsis } from '@/components'
import TreeSelectOrganization from '@/components/TreeSelectOrganization'

const searchArr = [
  {
    name: '新闻标题',
    value: 'title',
    type: 'input'
  },
  {
    name: '发布时间',
    value: 'releaseTime',
    type: 'dateRange',
    attr: {
      rangeFormat: ['releaseStartTime', 'releaseEndTime']
    }
  },
  {
    name: '新闻类别',
    value: 'type',
    type: 'select',
    data: Object.keys(NEWS_TYPE).map((key) => {
      return {
        label: NEWS_TYPE[key],
        value: key
      }
    })
  },
  {
    name: '作者',
    value: 'authorName',
    type: 'input'
  },
  {
    name: '来源',
    valueKey: 'orgId',
    type: TreeSelectOrganization,
    parentDisabled: true,
  }
]
const columns = [
  {
    title: '序号',
    width: 100,
    align: 'center',
    dataIndex: 'index',
    scopedSlots: { customRender: 'index' }
  },
  {
    title: '新闻类别',
    dataIndex: 'type',
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '新闻名称',
    dataIndex: 'title',
    width: '40%',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '来源',
    dataIndex: 'orgName',
    ellipsis: true
  },
  {
    title: '作者',
    dataIndex: 'authorName'
  },
  {
    title: '发布时间',
    dataIndex: 'releaseTime'
  }
]
export default {
  name: 'ReleasedNews',
  data() {
    return {
      searchArr,
      columns,
      totalInfo: {
        totalNum: 0
      },
      loadingState: {
        revoke: false,
        setTop: false,
        cancelTop: false,
        delete: false
      }
    }
  },
  components: {
    Ellipsis
  },
  methods: {
    /**
     * @description: 是否已阅读
     * @param {String}：id:新闻id
     * @return {*}
     */
    isViewed(id) {
      const readingQuantity = localStorage.getItem('readingQuantity') // 新闻阅读量缓存
      // 新闻阅读量缓存不存在或者缓存里没有当前新闻id
      if (!readingQuantity || !JSON.parse(readingQuantity)[id]) {
        return false
      } else {
        // 当前新闻是否存在当前登录阅读者id
        return JSON.parse(readingQuantity)[id].includes(this.$userInfo()?.id)
      }
    },
    /**
     * 过滤类别
     */
    filterLabel(val, key) {
      const keyMap = {
        type: NEWS_TYPE
      }
      return (keyMap[key] && keyMap[key][val]) || ''
    },
    async handleUpdate(data, actionType) {
      // 若操作是查看
      if (actionType === 'look') {
        // 若查看的是oa平台则打开外部链接
        if (data.sources === '2') {
          // 增加阅读量
          increaseReadingQuantity({ id: data.id }).then((res) => {
            if (res.code === 200) {
              let readingQuantity = localStorage.getItem('readingQuantity') // 新闻阅读量缓存
              // 若存在新闻阅读量缓存
              if (readingQuantity) {
                readingQuantity = JSON.parse(readingQuantity)
                // 若不存在当前新闻
                if (!readingQuantity[data.id]) {
                  readingQuantity[data.id] = []
                }
                readingQuantity[data.id].push(this.$userInfo()?.id)
              } else {
                // 添加当前新闻到缓存，且给当前新闻添加当前阅读者id
                readingQuantity = {
                  [data.id]: [this.$userInfo()?.id]
                }
              }
              // 缓存新闻阅读
              localStorage.setItem('readingQuantity', JSON.stringify(readingQuantity))
              // 刷新列表
              this.refreshTable(false)
            }
          })
          const Res = await getContentById({ id: data.id })
          if (Res?.data?.code === 200) {
            window.open(Res.data.message)
          }
          return
        }
      }
      const commonHandler = () => {
        this.$router.push({
          path: '/partyMasses/partyManage/newsManage/newsDetail',
          query: {
            pageType: actionType,
            id: data.id || ''
          }
        })
      }
      const actionMap = {
        look: commonHandler
      }
      actionMap[actionType] && actionMap[actionType](data)
    },
    async loadData(parameter) {
      const { pageNo, pageSize } = parameter
      const requestParameters = {
        pageNum: pageNo,
        pageSize,
        param: { ...this.queryParam, releaseStatus: 1 } // 已压缩
      }
      return getList2(requestParameters).then((res) => {
        this.totalInfo.totalNum = res.data.total
        return {
          data: res.data.list || [],
          code:res.code,
          currentPage: res.data.pageNum,
          totalSize: res.data.total
        }
      })
    },
    handleSearch(val) {
      val &&
        (this.queryParam = {
          ...val
        })
      this.refreshTable()
    },
    refreshTable(flag = true) {
      this.$refs.table.refresh(flag)
    }
  }
}
</script>